<template>
  <view class="index-container">
    <!-- 头部 -->
    <view class="header">
      <text class="header-title">资产管理</text>
      <view class="company-select">
        <uni-data-select v-model="selectedCompany" :localdata="companyList" :clear="false" placeholder="公司切换"
          @change="onCompanyChange"></uni-data-select>
      </view>
    </view>

    <!-- 轮播图 -->
    <swiper class="banner-swiper" :indicator-dots="true" indicator-color="rgba(255,255,255,0.5)"
      indicator-active-color="#fff" :autoplay="true" :circular="true">
      <swiper-item v-for="(item, index) in bannerList" :key="index">
        <image :src="item.image" class="banner-image" mode="aspectFill"></image>
      </swiper-item>
    </swiper>

    <!-- 资产列表 -->
    <view class="asset-list-section">
      <view class="section-header">
        <text class="section-title">资产列表</text>
        <view class="filter-text" @click="showFilterModal">筛选
          <view class="filter-icon">
            <text class="iconfont icon-shaixuan"></text>
          </view>
        </view>
      </view>
      <view class="asset-grid">
        <!-- 有数据时显示资产列表 -->
        <uni-grid v-if="assetList.length > 0" :column="2" :show-border="false" :highlight="false">
          <uni-grid-item v-for="(item, index) in assetList" :key="index">
            <view class="asset-card" @click="onGridItemClick(index, item)">
              <view class="asset-image-container">
                <image :src="item.image" class="asset-image" mode="aspectFill"></image>
                <view class="asset-tag">{{ item.type }}</view>
              </view>
              <view class="asset-info">
                <text class="asset-name">{{ item.name }}</text>
                <text class="asset-number">NO: {{ item.number }}</text>
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>

        <!-- 无数据时显示占位内容 -->
        <view v-else class="empty-container">
          <view class="empty-icon">📋</view>
          <text class="empty-text">暂无数据</text>
          <text class="empty-desc">请尝试调整筛选条件</text>
        </view>
      </view>

      <!-- 分页器 -->
      <view class="pagination-container" v-if="totalCount > 0 && assetList.length > 0">
        <uni-pagination :total="totalCount" :pageSize="filterForm.pageSize" :current="filterForm.pageNum"
          @change="onPageChange" show-icon="true" />
      </view>
    </view>

    <!-- 资产地图 -->
    <view class="asset-map-section">
      <view class="map-header">
        <text class="map-title">资产地图</text>
        <view class="search-container">
          <view class="search">
            <uni-easyinput v-model="searchKeyword" placeholder="请输入资产名称、编号"></uni-easyinput>
          </view>
          <button class="search-btn" @click="searchAssets">搜索</button>
        </view>
      </view>

      <view class="map-container">
        <map class="map" :latitude="mapCenter.latitude" :longitude="mapCenter.longitude" :markers="mapMarkers"
          :scale="mapScale" show-location @markertap="onMarkerTap"></map>
      </view>
    </view>
  </view>

  <!-- 筛选弹窗 -->
  <uni-popup ref="filterPopup" type="bottom" :mask-click="false">
    <view class="filter-modal">
      <view class="modal-header">
        <text class="modal-title">筛选条件</text>
        <text class="close-btn" @click="hideFilterModal">×</text>
      </view>

      <view class="modal-content">
        <!-- 编号输入 -->
        <view class="form-item">
          <text class="form-label">编号</text>
          <uni-easyinput v-model="filterForm.assetNumber" placeholder="请输入编号" class="form-input"></uni-easyinput>
        </view>

        <!-- 名称输入 -->
        <view class="form-item">
          <text class="form-label">名称</text>
          <uni-easyinput v-model="filterForm.assetName" placeholder="请输入名称" class="form-input"></uni-easyinput>
        </view>

        <!-- 分类选择 -->
        <view class="form-item">
          <text class="form-label">分类</text>
          <uni-data-select v-model="filterForm.assetType" :localdata="property_asset_type" :clear="true"
            placeholder="请选择资产类型" class="form-select"></uni-data-select>
        </view>

        <!-- 安全等级选择 -->
        <view class="form-item">
          <text class="form-label">安全等级</text>
          <uni-data-select v-model="filterForm.rankLv" :localdata="property_asset_rank" :clear="true"
            placeholder="请选择资产等级" class="form-select"></uni-data-select>
        </view>
      </view>

      <view class="modal-footer">
        <button class="btn-reset" @click="resetFilter">重置</button>
        <button class="btn-confirm" @click="confirmFilter">确认</button>
      </view>
    </view>
  </uni-popup>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { getSwiperImg } from '@/api/mian'
import { useDict } from '@/utils/dict'
import { getOwnCompany } from '@/api/system/fund/fundUtil.js'
import useConfigStore from '@/store/modules/company.js'
import useUserStore from '@/store/modules/user.js'
import { listAsset, assetMap } from '@/api/asset.js'

// 弹窗引用
const filterPopup = ref()

// 公司列表数据
const companyList = ref<Array<{ value: any; text: string }>>([])

// 选中的公司
const selectedCompany = ref('')

// 轮播图数据
const bannerList = ref([
  {
    image: ''
  }
])

// 资产列表数据
const assetList = ref<Array<{ image: string; type: string; name: string; number: string; assetId: string }>>([])

// 总数据量
const totalCount = ref(0)

// 筛选表单数据
const filterForm = ref<{
  pageNum: number;
  pageSize: number;
  assetNumber: string | null;
  assetName: string | null;
  assetType: string | null;
  rankLv: string | null;
  createCompany: string | null;
}>({
  pageNum: 1,
  pageSize: 4,
  assetNumber: null,
  assetName: null,
  assetType: null,
  rankLv: null,
  createCompany: null
})

// 获取字典数据
const dictData = useDict('property_asset_type', 'property_asset_rank')
const property_asset_type = (dictData as any).property_asset_type
const property_asset_rank = (dictData as any).property_asset_rank

// 页面加载时获取轮播图、字典数据和资产列表
onMounted(() => {
  fetchSwiperImg()
  useUserStore().getInfo()
  fetchCompanyList()
  // fetchAssetList() 会在 fetchCompanyList 中通过 onCompanyChange 调用
})

// 获取轮播图
const fetchSwiperImg = () => {
  getSwiperImg().then(res => {
    if (res.data && Array.isArray(res.data)) {
      // 通过拼接VITE_APP_BASE_URL和pictureUrl生成轮播图地址
      bannerList.value = res.data.map((item: { pictureUrl: string }) => ({
        image: import.meta.env.VITE_APP_BASE_URL + item.pictureUrl
      }))
    }
  }).catch(err => {
    console.error('获取轮播图失败:', err)
  })
}

// 获取资产列表
const fetchAssetList = async () => {
  try {
    // 确保用户信息已加载
    const userStore = useUserStore()
    if (!userStore.companyId) {
      await userStore.getInfo()
    }

    // 使用当前选中的公司ID，如果没有选中则使用用户默认公司ID
    if (!filterForm.value.createCompany) {
      filterForm.value.createCompany = userStore.companyId
    }

    console.log('请求参数:', filterForm.value)

    const res = await listAsset(filterForm.value)

    if (res.rows && Array.isArray(res.rows)) {
      // 保存总数据量
      totalCount.value = res.total || 0

      // 将后端数据转换为前端需要的格式
      assetList.value = res.rows.map((item: any) => {
        // 根据字典数据获取资产类型显示文字
        let typeText = ''
        if (property_asset_type && property_asset_type.value && Array.isArray(property_asset_type.value)) {
          const typeDict = property_asset_type.value.find((dict: any) => dict.value === item.assetType)
          if (typeDict) {
            typeText = typeDict.text
          }
        }

        // 处理图片地址，如果是逗号分隔的字符串，取第一张图片
        let imageUrl = ''
        if (item.assetImage) {
          const imageArray = item.assetImage.split(',').map((img: string) => img.trim()).filter((img: string) => img)
          imageUrl = imageArray.length > 0 ? imageArray[0] : ''
        }

        return {
          image: imageUrl ? import.meta.env.VITE_APP_BASE_URL + imageUrl : '',
          type: typeText,
          name: item.assetName,
          number: item.assetNumber,
          assetId: item.assetId
        }
      })
    }
    console.log('资产列表:', assetList.value, '总数量:', totalCount.value);

  } catch (err) {
    console.error('获取资产列表失败:', err)
  }
}

// 获取公司列表
const fetchCompanyList = async () => {
  try {
    // 先确保用户信息已加载
    const userStore = useUserStore()
    if (!userStore.companyId) {
      await userStore.getInfo()
    }

    // 再确保公司数据已加载
    const configStore = useConfigStore()
    if (configStore.companyList.length === 0) {
      await configStore.getCompanyList()
    }

    // 获取当前用户拥有的公司列表
    const companies = getOwnCompany()

    if (companies && Array.isArray(companies)) {
      // 将公司数据转换为下拉框需要的格式
      companyList.value = companies.map((company: any) => ({
        value: company.deptId,
        text: company.deptName
      }))
      // 如果有公司列表，默认选中第一个并触发切换事件
      if (companyList.value.length > 0) {
        selectedCompany.value = companyList.value[0].value
        // 手动触发公司切换事件，确保初始数据加载
        onCompanyChange(companyList.value[0].value)
      }
    }
  } catch (error) {
    console.error('获取公司列表失败:', error)
  }
}

// 显示筛选弹窗
const showFilterModal = () => {
  filterPopup.value.open()
  // 可以在这里添加其他逻辑，比如保存当前筛选状态等
}

// 隐藏筛选弹窗
const hideFilterModal = () => {
  filterPopup.value.close()
  // 重置筛选表单数据
  resetFilterForm()
}

// 重置筛选条件
const resetFilter = () => {
  const userStore = useUserStore()
  filterForm.value = {
    pageNum: 1,
    pageSize: 4,
    assetNumber: null,
    assetName: null,
    assetType: null,
    rankLv: null,
    createCompany: userStore.companyId
  }
}

// 重置筛选弹窗表单数据（不影响当前查询）
const resetFilterForm = () => {
  filterForm.value.assetNumber = null
  filterForm.value.assetName = null
  filterForm.value.assetType = null
  filterForm.value.rankLv = null
}

// 确认筛选
const confirmFilter = () => {
  console.log('筛选条件:', filterForm.value)
  // 重置页码到第一页
  filterForm.value.pageNum = 1
  // 重新获取资产列表
  fetchAssetList()
  hideFilterModal()
}

// 搜索关键词
const searchKeyword = ref('')

// 地图中心点
const mapCenter = ref({
  latitude: 30.871079,
  longitude: 105.388366
})

// 地图缩放级别
const mapScale = ref(14)

// 地图标记点
const mapMarkers = ref<any[]>([])
// 地图原始标记点（用于还原）
const originalMarkers = ref<any[]>([])

// 搜索资产
const searchAssets = () => {
  const keyword = (searchKeyword.value || '').trim()
  filterAndFocusMarkers(keyword)
}

// 初始化地图标点
const fetchAssetMap = async (companyId: any) => {
  try {
    const res: any = await assetMap({ createCompany: companyId })
    const rows = Array.isArray(res?.data) ? res.data : []
    const markers = rows
      .filter((p: any) => p && p.latitude != null && p.longitude != null)
      .map((p: any, idx: number) => ({
        id: p.assetId || idx + 1,
        latitude: Number(p.latitude),
        longitude: Number(p.longitude),
        iconPath: '/static/imgs/position.png',
        width: 30,
        height: 30,
        // 自定义字段用于筛选
        _address: p.address || '',
        label: {
          content: p.assetName || '',
          color: '#13227A',
          fontSize: 14,
          bgColor: '#fff',
          borderRadius: 8,
          borderWidth: 1,
          borderColor: '#000',
          anchorX: -50,
          anchorY: -50,
        }
      }))
    originalMarkers.value = markers
    mapMarkers.value = markers
    if (markers.length > 0) {
      mapCenter.value = { latitude: markers[0].latitude, longitude: markers[0].longitude }
    }
    // 如果搜索框里已有内容，则按关键词筛选
    const keyword = (searchKeyword.value || '').trim()
    if (keyword) {
      filterAndFocusMarkers(keyword)
    }
  } catch (error) {
    console.error('获取资产地图失败:', error)
    mapMarkers.value = []
  }
}

// 按关键词筛选标记并定位
const filterAndFocusMarkers = (keyword: string) => {
  const k = (keyword || '').trim().toLowerCase()
  if (!k) {
    // 还原全部标记
    mapMarkers.value = originalMarkers.value
    if (mapMarkers.value.length > 0) {
      mapCenter.value = { latitude: mapMarkers.value[0].latitude, longitude: mapMarkers.value[0].longitude }
    }
    return
  }
  const filtered = (originalMarkers.value || []).filter((m: any) => {
    const name = (m?.label?.content || '').toLowerCase()
    const addr = (m?._address || '').toLowerCase()
    return name.includes(k) || addr.includes(k)
  })
  mapMarkers.value = filtered
  if (filtered.length > 0) {
    mapCenter.value = { latitude: filtered[0].latitude, longitude: filtered[0].longitude }
  } else {
    uni.showToast({ title: '未找到匹配的标点', icon: 'none' })
  }
}

// 点击地图标记
const onMarkerTap = (e: any) => {
  console.log('点击了标记:', e.detail.markerId)
  // 跳转到资产详情页面
  uni.navigateTo({
    url: `/pages/index/children/asset-details?assetId=${e.detail.markerId}`
  })
}

// 公司切换事件
const onCompanyChange = (e: any) => {
  console.log('切换到公司:', e)
  // 更新公司ID
  filterForm.value.createCompany = e
  // 更新用户store中的companyId
  useUserStore().companyId = e
  // 重置页码到第一页
  filterForm.value.pageNum = 1
  // 重新获取资产列表
  fetchAssetList()
  // 同步获取地图标点
  fetchAssetMap(e)
}

// 分页切换事件
const onPageChange = (e: any) => {
  console.log('切换到第', e.current, '页')
  // 更新页码
  filterForm.value.pageNum = e.current
  // 重新查询数据
  fetchAssetList()
}

// 网格项点击事件
const onGridItemClick = (index: number, item: any) => {
  console.log('点击了第', index, '个网格，资产信息:', item)
  
  // 检查资产ID是否存在
  if (!item.assetId) {
    console.error('资产ID不存在:', item)
    uni.showToast({
      title: '资产信息不完整',
      icon: 'none'
    })
    return
  }
  
      // 跳转到资产详情页面，传递资产ID
    uni.navigateTo({
      url: `/pages/index/children/asset-details?assetId=${item.assetId}`,
      success: () => {
        console.log('跳转成功，资产ID:', item.assetId)
      },
      fail: () => {
        console.error('跳转失败')
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
}
</script>

<style lang="scss" scoped>
.index-container {
  height: 100vh;
  background-color: #f5f5f5;
  overflow-y: auto;
  padding-bottom: 40rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.company-select {
  width: 350rpx;
}

.banner-swiper {
  height: 300rpx;
  margin-bottom: 0;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.asset-list-section {
  background-color: #fff;
  padding: 30rpx;
  margin-top: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.filter-text {
  display: flex;
  gap: 10rpx;
  align-items: center;
  font-size: 24rpx;
}

.filter-icon .iconfont {
  font-size: 30rpx;
  color: #666;
}

.asset-grid {
  margin-bottom: 30rpx;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20rpx 0;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  min-height: 400rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #ccc;
}

.asset-card {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 20rpx;
  height: 100%;
}


.asset-image-container {
  position: relative;
  height: 200rpx;
}

.asset-image {
  width: 100%;
  height: 100%;
}

.asset-tag {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  background: #FFD700;
  color: #333;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.asset-info {
  padding: 20rpx;
}

.asset-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.asset-number {
  display: block;
  font-size: 24rpx;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 筛选弹窗样式 */
.filter-modal {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 20rpx 30rpx 110rpx 30rpx;
  max-height: 80vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.form-input {
  width: 100%;
}

.form-select {
  width: 100%;
}

.modal-footer {
  display: flex;
  gap: 20rpx;
}

.btn-reset {
  flex: 1;
  height: 80rpx;
  background: #f5f5f5;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  color: #666;
  font-size: 28rpx;
}

.btn-confirm {
  flex: 1;
  height: 80rpx;
  background: #409EFF;
  border: none;
  border-radius: 8rpx;
  color: #fff;
  font-size: 28rpx;
}

::v-deep .filter-modal .uni-select__selector {
  top: unset !important;
  bottom: calc(100% + 8px) !important;
  /* 100%是输入框高度，8px是间距 */
  transform-origin: center bottom !important;
  /* 调整弹出动画原点 */
}

/* 资产地图样式 */
.asset-map-section {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 30rpx;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.map-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.search-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 20rpx;
  flex: 1;
}

.search {
  width: 300rpx;
}

.search-btn {
  color: #000;
  border: 1rpx solid #E5FFFF;
  border-radius: 8rpx;
  font-size: 26rpx;
  white-space: nowrap;
  margin: 0;
}

.map-container {
  width: 100%;
  border-radius: 16rpx;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 500rpx;
}


::v-deep .uni-select__input-box {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
